const baseUrl = 'https://wechat.cclx.top/index.php'
const http = {
	// is_token true不需要token，false需要
	isRefertoken: false,
	isModalShown: false, //401弹框
	post(url, data, header = {}) {
		return this.request('POST', url, data, header)
	},
	get(url, data, header = {}) {
		return this.request('GET', url, data, header)
	},
	put(url, data, header = {}) {
		return this.request('PUT', url, data, header)
	},
	del(url, data, header = {}) {
		return this.request('delete', url, data, header)
	},
	checkToken(callback) {
		if (this.isRefertoken) {
			setTimeout(() => {
				this.checkToken(callback);
			}, 100);
		} else {
			return callback();
		}
	},
	delayback(data) {

		if (data.delaytime_) {
			setTimeout(() => {
				uni.navigateBack({
					delta: 1
				})
			}, 1500)
		}
	},
	myShowToast(res) {

	},
	callBackFun(is_token, callback) {
		if (is_token) return callback();
		this.checkToken(() => {
			var thetime = Date.parse(new Date()) / 1000;
			var tokenData = uni.getStorageSync('tokenData').token;
			if (tokenData && tokenData.expiresTime) {
				var time = tokenData.expiresTime - 200;
				if (thetime >= time) {
					var token = '';
					var tokenData = uni.getStorageSync('tokenData').token;
					if (tokenData) token = tokenData.token;

					this.isRefertoken = true;
					uni.request({ //无感刷新
						url: baseUrl + '/member/auth/refresh-token',
						header: {
							token: token,
							'platform': 'WechatMiniProgram'
						},
						data: {
							refreshToken: tokenData.refreshToken
						},
						method: 'POST',
						success: (res) => {
							this.isRefertoken = false;
							uni.hideLoading();
							if (res.data.code == 0) {
								return callback();
							}
						},
						fail: (res) => {
							return callback();
						}
					})
				} else {
					return callback();
				}
			} else {
				return callback();
			}
		})
	},
	request(method, url, dat = {}, header = {}) {
		// uni.showLoading({
		// 	title: '加载中'
		// })
		let data = dat
		console.log('dat6a', data)
		var token = '';
		var tokenData = uni.getStorageSync('token');
		if (tokenData) token = tokenData;
		header['token'] = token
		header['platform'] = 'WechatMiniProgram'
		if (token) {
			header['token'] = token
		}
		return new Promise((resolve, reject) => {
			var requestTask = uni.request({
				method: method,
				url: baseUrl + url,
				data: data,
				header: header,
				success: (res) => {
					uni.hideLoading();
					if (res.data.code != 0 && res.data.code != 200) {
						if (res.data.msg == '账号未登录' || res.data.msg == 'invalid' ||
							res.data.code == 401) {
							uni.clearStorageSync();
						} else {
							resolve(res.data);
						}
					} else {
						resolve(res.data);
					}
				},
				fail: (err) => {
					uni.hideLoading();
					reject(err.data);
				},
				complete: () => {
					uni.stopPullDownRefresh();
				}
			})
		})
	},


}

export {
	http,
	baseUrl
}